import string
import hashlib
from random import choice
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired
from flask import current_app
from .errors import APIError

auth = HTTPTokenAuth(scheme='JWT')


@auth.verify_token
def verify_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
        print(data)
    except BadSignature:
        raise APIError(code=403, msg='token不正确')
    except SignatureExpired:
        raise APIError(code=403, msg='token过期')
    return True


def create_token(user_id):
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=current_app.config['TOKEN_EXPIRATION'])
    token = s.dumps({"id": user_id}).decode('ascii')
    return token


def create_salt(length=16):
    chars = list(string.ascii_lowercase + string.digits)
    return ''.join([choice(chars) for i in range(length)])


def create_password(raw):
    salt = create_salt()
    password = '{0}{1}'.format(salt, raw)
    _hash = hashlib.sha1(password.encode('utf-8')).hexdigest()
    return "%s$%s" % (salt, _hash)


def check_password(raw, password):
    if '$' not in password:
        return False
    salt, _hash = password.split('$')
    pwd = '{0}{1}'.format(salt, raw)
    verify = hashlib.sha1(pwd.encode('utf-8')).hexdigest()
    return verify == _hash
